#!/usr/bin/env python
import os,sys

def auto_reload(*module_names):
    for module_name in module_names:
        try:
            module=sys.modules[module_name]
        except Exception,e:
            print e
            continue
        try:
            reload(module)
        except Exception,e:
            print e
        
def import_object(name,path=None):
    if path is not None:
        sys.path.append(path)
    parts=name.rsplit('.',1)
    module=None
    try:
        module= __import__(name)
    except ImportError:
        if len(parts)<2:
            raise
    if module is not None:
        return module
    module_name,attr_name=parts
    __import__(module_name)
    module=sys.modules[module_name]
    try:
        attr=getattr(module,attr_name)
    except AttributeError:
        raise ImportError('No attribute named %s' % attr_name)
    return attr

def get_pypath():
    import re
    s=str(reload(os))
    p=r'^.*from\s\'(.+?)'+os.sep+'lib.*$'
    m=re.match(p,s)
    path=m.group(1)
    if path.endswith(os.sep):
        path=path[:-1]
    return path

def get_sppath():
    import re
    import MySQLdb
    s=str(reload(MySQLdb))
    p=r'^.*from\s\'(.+?)'+os.sep+'MySQL.*$'
    m=re.match(p,s)
    path=m.group(1)
    if path.endswith(os.sep):
        path=path[:-1]
    return path

def import_path(path=os.getenv('PY_HOME'),pth='mypy.pth'):
    sppath=get_sppath()
    mypy_file=sppath+os.sep+pth
    paths={}
    if os.path.exists(mypy_file):
        f=open(mypy_file,'r')
        for line in f:
            if not line or line.startswith('#'):
                continue
            line=line[:-1]
            paths[line]=1
        f.close()
    if path.endswith(os.sep):
        path=path[:-1]
    f=open(mypy_file,'a')
    if path not in paths:
        f.write(path+'\n')
    f.close()

if __name__ == '__main__':
    print import_object('wwpy.io.Sock.SockIO',path=os.getenv('PY_HOME'))
    print get_sppath()
    import_path()
